package com.vhall.component.plugin.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.vhall.component.framework.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * @author yuanzh
 * Json工具类
 */
@Slf4j
public final class JsonUtil {

    /**
     * 将map转成json字符串
     *
     * @param map
     * @return
     */
    public static String map2Json(Map map) {
        return JSON.toJSONString(map);
    }

    /**
     * 将json字符串转成map
     *
     * @param str
     * @return
     */
    public static Map string2Map(String str) {
        return objectFromJSONString(str, Map.class);
    }

    public static final <T> List<T> arrayFromJSONString(String jsonString, Class<T> clazz) {
        return JSON.parseArray(jsonString, clazz);
    }

    public static final <T> T objectFromJSONString(String jsonString, Class<T> clazz) {
        return JSON.parseObject(jsonString, clazz);
    }

    public static final <T> T objectFromJSONString(String jsonString, Class<T> clazz, Feature... features) {
        return JSON.parseObject(jsonString, clazz, features);
    }

    public static final <T> String toJsonString(T t) {
        if (null != t) {
            return JSON.toJSONString(t, SerializerFeature.DisableCircularReferenceDetect);
        }
        return null;
    }


    public static String getJsonValue(String resContent, String key) {
        if (StringUtils.isNotEmpty(resContent) && StringUtils.isNotEmpty(key)) {
            try {
                JSONObject jsonObject = JSONObject.parseObject(resContent);
                return jsonObject.getString(key);
            } catch (Exception e) {
                log.error("getJsonValue exception", e);
            }
        }
        return null;
    }
}
